package com.muqi.app.qlearn.student.org;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.flyco.banner.anim.select.RotateEnter;
import com.flyco.banner.anim.unselect.NoAnimExist;
import com.flyco.widget.BannerItem;
import com.muqi.app.im.ui.ChatActivity;

import com.muqi.app.network.http.GlideImageUtils;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.qlearn.modles.CreditBean;
import com.muqi.app.qlearn.modles.GroupTeacherInfoCourseEntity;
import com.muqi.app.qlearn.modles.MediaInfo;
import com.muqi.app.qlearn.modles.OrganizeList;
import com.muqi.app.qlearn.student.BaseFragmentActivity;
import com.muqi.app.qlearn.student.R;

import com.muqi.app.user.widget.CircularImageView;
import com.muqi.app.user.widget.SimpleImageBanner;
import com.muqi.app.widget.scanpicture.ScanPictureActivity;

public class TeacherInfoActivity extends BaseFragmentActivity {
	private PagerSlidingTabStrip tab;
	private ViewPager viewPager;
	private ScrollableLayout scroll;

	private ArrayList<ScrollAbleFragment> fragmentList;
	private TeacherFragmentPagerAdapter myFragmentPagerAdapter;
	private List<String> titleList;
	
	private List<MediaInfo> mediaList = new ArrayList<MediaInfo>();
	private ArrayList<String> bigUrls = new ArrayList<String>();

	private List<GroupTeacherInfoCourseEntity> mCourseList = new ArrayList<GroupTeacherInfoCourseEntity>();
	private int mOneToOneItemNum = 0;
	private int mClassItemNum = 0;

	private String mUserId;

	private SimpleImageBanner topBanners;
	private boolean hasPrepared = false;

	private TextView mTeacherName;
	private TextView mTeacherAge;
	private TextView mTeacherAuth;
	private TextView mTeacherComment;
	private TextView mTeacherVisit;

	private CircularImageView mTeacherImage;

	private Button mTeacherTel;
	private Button mServiceTel;

	private String mTeacherChat_id = "";
	private String mServiceTelNum = "";

	private OrganizeList organizeList;

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_teacher_info);
	}

	@Override
	protected void onInit() {
		scroll = (ScrollableLayout) findViewById(R.id.teacher_info_scroll);
		tab = (PagerSlidingTabStrip) findViewById(R.id.pagertab);
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		topBanners = (SimpleImageBanner) findViewById(R.id.home_simple_banner);

		mTeacherName = (TextView) findViewById(R.id.teacher_name);
		mTeacherAge = (TextView) findViewById(R.id.teacher_age);
		mTeacherAuth = (TextView) findViewById(R.id.teacher_auth);
		mTeacherComment = (TextView) findViewById(R.id.teacher_comment);
		mTeacherVisit = (TextView) findViewById(R.id.teacher_visit);

		mTeacherImage = (CircularImageView) findViewById(R.id.teacher_image);
		mTeacherImage.setBorderWidth(10);
		mTeacherImage.setBorderColor(Color.parseColor("#ffffff"));

		mTeacherTel = (Button) findViewById(R.id.teacher_consult);
		mServiceTel = (Button) findViewById(R.id.service_consult);

		
		mTeacherTel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!TextUtils.isEmpty(mTeacherChat_id)) {
					startActivity(new Intent(TeacherInfoActivity.this, ChatActivity.class).putExtra("userId", mTeacherChat_id));
				}else{
					showToast("未获取到该教师聊天账号");
				}
			}
		});
		mServiceTel.setOnClickListener(new OnClickListener() {
				
			@Override
			public void onClick(View arg0) {
				if (!TextUtils.isEmpty(mServiceTelNum)) {
					Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ mServiceTelNum));
					startActivity(intent);
				}else{
					showToast("还未有客服");
				}
			}
		});
	}

	@Override
	protected void onData() {
		mUserId = getIntent().getStringExtra("userid");
		if (!TextUtils.isEmpty(mUserId)) {
			loadingData();
		}else{
			mUserId="0";
		}
	}

	@Override
	protected void onResume() {
		if (hasPrepared) {
			topBanners.startScroll();
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		if (hasPrepared) {
			topBanners.pauseScroll();
		}
		super.onPause();
	}

	private void loadingData() {
		showLoading();
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("token", mSpUtil.getToken());
		params.put("userid", mUserId);
		String requestApi = ParamsUtils.buildParams(NetWorkApi.GET_TEACHER_INFO_API, params);

		MyAsyncHttp.getCacheDataAbsolutelyHttp(this, requestApi,
				new AsyncCallBackListener() {

					@Override
					public void onAsyncCallBack(RESULTCODE resuleCode,String request, String result) {
						hideLoading();
						if (resuleCode == RESULTCODE.LOCAL|| resuleCode == RESULTCODE.SUCCESS) {
							try {
								
								
								List<CreditBean> listData = new ArrayList<CreditBean>();

								JSONObject resultAllata = new JSONObject(result.toString());
								JSONObject data = resultAllata.getJSONObject("data");
							
							
								
								JSONArray jsonComment = data.getJSONArray("commentList");
								
								JSONObject jsonOrg=data.getJSONObject("organization");
								if(jsonOrg!=null){

							        TeacherInfoActivity.this.organizeList=OrganizeList.fromJson(jsonOrg);
								}
								int commentNum = jsonComment.length();
								if(commentNum>0){
									for (int i = 0; i < commentNum; i++) {
										JSONObject object = jsonComment.optJSONObject(i);
										CreditBean item = CreditBean
												.fromJson(object);
										listData.add(item);
									}
								}
										
								
								JSONArray picList = data.getJSONArray("photolist");
								if (picList.length() > 0) {
									
									mediaList.clear();
									for (int i = 0; i < picList.length(); i++) {
										MediaInfo info = null;
										info = MediaInfo.fromJson(picList.optJSONObject(i));
										if(info!=null){
											mediaList.add(info);
										}
									}
									showTopAdsView();
								}
								
								mTeacherChat_id = data.getString("im_user_id");
								HashMap<String, String> intro = new HashMap<String, String>();
								intro.put("introduce",data.getString("introduce").trim());
								intro.put("tacching_texperience", data.getString("tacching_texperience").trim());
								intro.put("teaching_share",data.getString("teaching_share").trim());
								intro.put("tedian", data.getString("tedian").trim());

								initFragmentPager(viewPager, tab, scroll,
										mCourseList, mOneToOneItemNum,
										mClassItemNum, intro,listData);

								mTeacherName.setText(data.getString("name"));
								if (TextUtils.isEmpty(data
										.getString("jiaoling"))) {
									mTeacherAge.setText("0年教龄");
								} else {
									mTeacherAge.setText(data
											.getString("jiaoling") + "年教龄");
								}
								if (TextUtils.isEmpty(data
										.getString("total_authentication"))) {
									mTeacherAuth.setText("0项认证");
								} else {
									mTeacherAuth.setText(data
											.getString("total_authentication")
											+ "项认证");
								}
								if (TextUtils.isEmpty(data
										.getString("total_comment"))) {
									mTeacherComment.setText("0条评论");
								} else {
									mTeacherComment.setText(data
											.getString("total_comment") + "条评论");
								}
								if (TextUtils.isEmpty(data.getString("hits"))) {
									mTeacherVisit.setText("0人访问");
								} else {
									mTeacherVisit.setText(data
											.getString("hits") + "人访问");
								}

								if (!TextUtils.isEmpty(data.getString("avatar"))) {
									GlideImageUtils.setAvatar(
											TeacherInfoActivity.this,
											data.getString("avatar"), mTeacherImage);
								}

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}
				}, 1);

	}



	protected void showTopAdsView() {
		List<BannerItem> adListInfo = new ArrayList<BannerItem>();
		for (MediaInfo item : mediaList) {
			BannerItem info = null;
			info = new BannerItem();
			info.imgUrl = item.fileurl_03;
			info.title = "";
			adListInfo.add(info);
			bigUrls.add(item.fileurl_00);
		}
		topBanners.setSelectAnimClass(RotateEnter.class)
				.setUnselectAnimClass(NoAnimExist.class).setDelay(3)
				.setPeriod(3).setSource(adListInfo).startScroll();
		topBanners.setOnItemClickL(new SimpleImageBanner.OnItemClickL() {

			@Override
			public void onItemClick(int position) {
				Intent intent = new Intent(TeacherInfoActivity.this, ScanPictureActivity.class);
				intent.putExtra(ScanPictureActivity.EXTRA_IMAGE_URLS, bigUrls);
				intent.putExtra(ScanPictureActivity.EXTRA_IMAGE_INDEX, position);
				startActivity(intent);
			}
		});
		hasPrepared = true;
	}

	private void initFragmentPager(ViewPager viewPager,
			PagerSlidingTabStrip pagerSlidingTabStrip,
			final ScrollableLayout mScrollLayout,
			List<GroupTeacherInfoCourseEntity> mCourseList2,
			int mOneToOneItemNum2, int mClassItemNum2,
			HashMap<String, String> intro, List<CreditBean> listData) {
		fragmentList = new ArrayList<ScrollAbleFragment>();

		
		fragmentList.add(HomeFragment.newInstance(mCourseList2,mOneToOneItemNum2, mClassItemNum2, intro,organizeList));
		fragmentList.add(CommentFragment.newInstance(listData));

		titleList = new ArrayList<String>();
		titleList.add("教师详情");
		titleList.add("课程评价");

		myFragmentPagerAdapter = new TeacherFragmentPagerAdapter(
				getSupportFragmentManager(), fragmentList, titleList);

		viewPager.setAdapter(myFragmentPagerAdapter);

		myFragmentPagerAdapter = new TeacherFragmentPagerAdapter(
				getSupportFragmentManager(), fragmentList, titleList);

		viewPager.setAdapter(myFragmentPagerAdapter);
		/**
		 * 标注当前页面,从而ScrollableLayout可以从该ListFragment取到当前嵌套的listview,
		 * 剩下的就交给ScrollableLayout去处理了
		 **/
		mScrollLayout.getHelper().setCurrentScrollableContainer(
				fragmentList.get(0));
		pagerSlidingTabStrip.setViewPager(viewPager);
		pagerSlidingTabStrip
				.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
					@Override
					public void onPageScrolled(int i, float v, int i2) {

					}

					@Override
					public void onPageSelected(int i) {
			
						/**
						 * 页面切换时,标注当前页面,
						 * 从而ScrollableLayout可以从该ListFragment取到当前嵌套的listview
						 * ,剩下的就交给ScrollableLayout去处理了
						 **/
						mScrollLayout.getHelper()
								.setCurrentScrollableContainer(
										fragmentList.get(i));
					}

					@Override
					public void onPageScrollStateChanged(int i) {

					}
				});
		viewPager.setCurrentItem(0);
	}

	public void onBack(View v) {
		this.finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	public class TeacherFragmentPagerAdapter extends FragmentPagerAdapter {

		private List<ScrollAbleFragment> fragmentList;
		private List<String> titleList;

		public TeacherFragmentPagerAdapter(FragmentManager fm,
				List<ScrollAbleFragment> fragmentList, List<String> titleList) {
			super(fm);
			this.fragmentList = fragmentList;
			this.titleList = titleList;
		}

		@Override
		public Fragment getItem(int position) {
			return fragmentList.get(position);
		}

		@Override
		public int getCount() {
			return fragmentList.size();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return titleList.get(position);
		}
	}

	@Override
	protected void onDestroy() {
		if (hasPrepared) {
			topBanners.removeAllViews();
			topBanners.destroyDrawingCache();
		}
		super.onDestroy();
	}

}
